package day04;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/4/11
 */
public class NineSquareGrid {
    public static void main(String[] args) {
        int[][] grid = new int[3][3];
        int row = 0;
        int col = 3 / 2;
        grid[row][col] = 1;
        for (int num = 2; num <= 9; num++) {
            // 尝试右上角位置
            int nextRow = row - 1;
            int nextCol = col + 1;

            // 处理越界情况
            if (nextRow < 0 && nextCol >= 3) {
                // 行列都越界
                nextRow = row + 1;
                nextCol = col;
            } else if (nextRow < 0 ) {
                // 行越界，列不越界
                nextRow = 3 - 1;
            } else if (nextCol >= 3 ) {
                // 列越界，行不越界
                nextCol = 0;
            }

            // 检查右上角是否已有值
            if (grid[nextRow][nextCol] != 0) {
                // 有值，填在前一个元素的正下方
                nextRow = row + 1;
                nextCol = col;
            }

            // 填入数字
            grid[nextRow][nextCol] = num;

            // 更新当前位置
            row = nextRow;
            col = nextCol;
        }

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(grid[i][j] + " ");
            }
            System.out.println();

        }
    }
}
